//
//  XJComposeViewController.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/25.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import SVProgressHUD


class XJComposeViewController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
     override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    // MARK: - 布局界面,添加控件和约束
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view).offset(5)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
         
            make.leading.equalTo(5)
            make.top.equalTo(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        //通知监听键盘的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "XJEmoticonBtnClick:", name: "XJEmoticonBtnClickNotification", object: nil)
        //表情键盘删除按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "XJEmoticonDeleteBtnClick", name: "XJEmoticonDeleteBtnClickNotificaton", object: nil)
    }
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
        
    }

    // MARK: - 监听事件
    //表情键盘删除按钮点击
    @objc private func XJEmoticonDeleteBtnClick() {
        //回删
        textView.deleteBackward()
    
    }
    //点击表情按钮
    @objc private func XJEmoticonBtnClick(noti: NSNotification) {
    
           let emoticon = noti.userInfo!["emoticon"] as! XJEmojiModel
            //判断是否是emoji表情
        if emoticon.type == "1" {
        
            textView.insertText((emoticon.code! as NSString).emoji())
        }else{

            textView.insertEmoticon(emoticon)
        }
    }
    //键盘改变
    @objc private func keyboardChangeFrame(noti: NSNotification) {
    
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        composeToolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    /**
     点击返回按钮
     */
   @objc private func back() {
    
        self.textView.endEditing(true)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    /**
     点击发送按钮
     */
    @objc private func send(){
        
        if pictureView.hidden{
            sendTextData()
        }else{
            sendPicData()
        }
    }
    
    /**
     发送图片微博
     */
    private func sendPicData() {
        
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        //参数
        let params = [
            "access_token":XJUserAccountModel.sharedModel.account?.access_token ?? "",
            "status":textView.emoticonText!
        ]
        
        //发送请求
        let data = UIImagePNGRepresentation(self.pictureView.imageArr.first!)!
        XJNetworkTools.sharedTools.upload(urlStr, parameters: params, datas:["pic": data]) { (responseObject, error) -> () in
            
            if error == nil {
                
                SVProgressHUD.showInfoWithStatus("发送成功")
            }else{
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
                    print("\(error)")
            }
        }
    }
    /**
     发送文字微博
     */
    private func sendTextData() {
        
        //地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        //参数
        let params = [
            "access_token":XJUserAccountModel.sharedModel.account?.access_token ?? "",
            "status":textView.emoticonText!
        ]
        
        //发送请求
        XJNetworkTools.sharedTools.request(XJRequestMethod.Post, url: urlStr, parameters: params) { (responseObject, error) -> () in
            
            if error == nil {
                
                SVProgressHUD.showInfoWithStatus("发送成功")
            }else{
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                print("\(error)")
                return
            }
        }
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    
    
    // MARK: - 懒加载控件
    
    //表情键盘
    private lazy var emojiKeyboard: XJEmojiKeyboard = {
    
        let keyboard = XJEmojiKeyboard()
        keyboard.frame.size = CGSize(width: SCREENW, height: 228)
        
        return keyboard
    }()
    
    //照片选择view
    private lazy var pictureView: XJPictureView = {
    
        let picView = XJPictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        picView.selectedPicClosure = { [weak self] in
        
            self?.selectPicture()
        }
        
        return picView
    }()
    
    /// 懒加载导航控制器中间的文字label
    private lazy var titleView: UILabel = {
    
        let label = UILabel(textColor: UIColor.blackColor(), fontSize: 15)
        label.textAlignment = .Center
        label.numberOfLines = 0
        
        if let name = XJUserAccountModel.sharedModel.account?.name {

            let text = "发微博\n\(name)"
            //name所在字符串范围
            let range = (text as NSString).rangeOfString(name)
            let attText = NSMutableAttributedString(string: text)
            
            attText.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)],range: range)
            
            //富文本
            label.attributedText = attText        
        }else{
        
            label.text = "发微博"
        }
            label.sizeToFit()
        
        return label
    
    }()
    
    
    /// 懒加载textView
    private lazy var textView: XJTextView = {
    
        let textView = XJTextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(16)
        textView.alwaysBounceVertical = true
        //拖拽的时候键盘消失
        textView.keyboardDismissMode = .OnDrag
        
        return textView
    
    }()
    
    
    /// 懒加载右侧按钮
    private lazy var rightBtn: UIButton = {
    
        let btn = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        btn.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        btn.setTitle("发送", forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.frame.size = CGSize(width: 45, height: 28)
        
        return btn
    
    }()
    
    /// 懒加载底部toolBar
    private lazy var composeToolBar: XJComposeToolBar = {
    
        let toolBar = XJComposeToolBar(frame: CGRectZero)
        
        //执行闭包
        toolBar.buttonClickClosure = { (type: XJComposeToolBarButtonType) in
            
            switch type {
                
            case .Picture:
                self.selectPicture()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self.switchKeyboard()
                break
            case .Add:
                break
                
            }
        }
        
        return toolBar
    }()
    
    // MARK: - composeToolBar按钮点击,执行方法
    /**
     切换表情键盘
     */
    private func switchKeyboard() {
    
        textView.inputView = textView.inputView == nil ? emojiKeyboard : nil
        composeToolBar.isSystemKeyboard = textView.inputView == nil
        textView.reloadInputViews()
        
        if !textView.isFirstResponder(){
            textView.becomeFirstResponder()
        }
    }
    
    /**
     点击选择图片,pickerVC的代理中实现添加图片
     */
    private func selectPicture() {
    
        let vc = UIImagePickerController()
        vc.delegate = self
        
        self.presentViewController(vc, animated: true, completion: nil)
    
    }
    
}

// MARK: - ImagePickerControllerDelegate
extension XJComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let img = image.scaleToWidth(600)
        pictureView.addImage(img)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

extension XJComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
